package com.sws.person.config;

import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * RestTemplate配置类
 * 用于配置全局RestTemplate实例，适应内网穿透场景下的网络延迟
 */
@Configuration
public class RestTemplateConfig {
    
    private static final Logger logger = LoggerFactory.getLogger(RestTemplateConfig.class);

    @Value("${http.client.connect-timeout}")
    private int connectTimeout;
    
    @Value("${http.client.read-timeout}")
    private int readTimeout;
    
    @Value("${http.client.connection-request-timeout}")
    private int connectionRequestTimeout;
    
    /**
     * 在Bean初始化后输出超时配置信息
     */
    @PostConstruct
    public void init() {
        logger.info("=================================================");
        logger.info("RestTemplate配置加载完成，HTTP客户端超时配置如下：");
        logger.info("连接超时时间(connect-timeout): {}毫秒", connectTimeout);
        logger.info("读取超时时间(read-timeout): {}毫秒", readTimeout);
        logger.info("连接请求超时时间(connection-request-timeout): {}毫秒", connectionRequestTimeout);
        logger.info("=================================================");
    }

    /**
     * 创建RestTemplate Bean，配置较长的超时时间
     * 
     * @return RestTemplate实例
     */
    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory());
        logger.info("已创建配置了超时参数的RestTemplate Bean");
        return restTemplate;
    }
    
    /**
     * 配置ClientHttpRequestFactory，设置连接超时和读取超时
     * 
     * @return ClientHttpRequestFactory
     */
    private ClientHttpRequestFactory clientHttpRequestFactory() {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        // 使用配置文件中的超时设置
        factory.setConnectTimeout(connectTimeout);
        factory.setConnectTimeout(readTimeout);
        factory.setConnectionRequestTimeout(connectionRequestTimeout);
        return factory;
    }
} 